import type { PlaceholderModel } from '../../../Form'
import { IsUtils } from 'fetm-utils'
import { type ETableColumn, ETableComponentNameEnum } from '../types'

/**
 * 驼峰转横杠
 */
export function humpToDash(str: string): string {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}

/**
 * 首字母大写
 */
export function firstUpperCase(str: string) {
  return str.toLowerCase().replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

/**
 * @param slotsProps 插槽属性
 */
export function setItemComponentSlots(slotsProps: Record<string, any> = {}): Record<string, any> {
  const slotObj: Record<string, any> = {}
  for (const key in slotsProps) {
    if (slotsProps[key]) {
      if (IsUtils.isFunction(slotsProps[key])) {
        slotObj[humpToDash(key)] = (...args: any[]) => {
          return slotsProps[key]?.(...args)
        }
      }
      else {
        slotObj[humpToDash(key)] = () => {
          return slotsProps[key]
        }
      }
    }
  }
  return slotObj
}

/**
 *
 * @param item 传入的组件属性
 * @returns 默认添加 clearable 属性
 */
export function setComponentProps(item: ETableColumn): Record<string, any> {
  // const notNeedClearable = ['ColorPicker']
  // 拆分事件并组合
  const onEvents = (item?.componentProps as any)?.on || {}
  const newOnEvents: Record<string, any> = {}

  for (const key in onEvents) {
    if (onEvents[key]) {
      newOnEvents[`on${firstUpperCase(key)}`] = (...args: any[]) => {
        onEvents[key](...args)
      }
    }
  }

  const componentProps: Record<string, any> = {
    clearable: true,
    ...item.componentProps,
    ...newOnEvents,
  }
  // 需要删除额外的属性
  if (componentProps.slots)
    delete componentProps.slots

  if (componentProps.on)
    delete componentProps.on

  return componentProps
}

/**
 *
 * @param schema 对应组件数据
 * @returns 返回提示信息对象
 * 用于自动设置placeholder
 */
export function setTextPlaceholder(schema: ETableColumn): PlaceholderModel {
  const textMap = [
    ETableComponentNameEnum.INPUT,
    ETableComponentNameEnum.AUTOCOMPLETE,
    ETableComponentNameEnum.INPUT_NUMBER,
  ]
  const selectMap = [
    ETableComponentNameEnum.SELECT,
    ETableComponentNameEnum.TIME_PICKER,
    ETableComponentNameEnum.DATE_PICKER,
    ETableComponentNameEnum.TIME_SELECT,
    ETableComponentNameEnum.SELECT_V2,
  ]
  if (textMap.includes(schema?.component as ETableComponentNameEnum)) {
    return {
      placeholder: '请输入',
    }
  }
  if (selectMap.includes(schema?.component as ETableComponentNameEnum)) {
    // 一些范围选择器
    const twoTextMap = [
      'datetimerange',
      'daterange',
      'monthrange',
      'datetimerange',
      'daterange',
    ]
    if (
      twoTextMap.includes(
        ((schema?.componentProps as any)?.type
          || (schema?.componentProps as any)?.isRange) as string,
      )
    ) {
      return {
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间',
        rangeSeparator: '-',
      }
    }
    else {
      return {
        placeholder: '请选择',
      }
    }
  }
  return {}
}
